package com.jackrain.nea.omslocal.Dao;

import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.omslocal.service.GetSqunceService;
import com.jackrain.nea.omslocal.service.LocalLogService;
import com.jackrain.nea.omslocal.service.SendMqServies;
import com.jackrain.nea.omslocal.util.JsonKeyCheck;
import com.jackrain.nea.omslocal.util.PackageJsonSqlUtil;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.Tools;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.util.Date;
import java.util.Set;

/**
 * discription: 京东商品下载
 * Created with IntelliJ IDEA.
 * @author wcy
 * @date 2018/5/3 10:25:00
 */
@Slf4j
@Component
public class JingDongItemDao {

    @Autowired
    private LocalLogService localLogService;

    @Autowired
    private GetSqunceService getSqunceService;

    @Autowired
    private PackageJsonSqlUtil packageJsonSqlUtil;

    @Autowired
    private PropertiesConf pconf;

    @Autowired
    private SendMqServies sendMqServies;

    public void itemStart(JSONObject tempObj, String msgkey, String topic, String tag) {
        JSONObject retObj = new JSONObject();
        JingDongItemDao jingDongItemDao = ApplicationContextHandle.getBean(JingDongItemDao.class);
        String jdLogRetTopic = pconf.getProperty("ons.jdLogRetTopic", "");
        int countFaild = 0;
        String sellerNick = null;
        StringBuffer tids = new StringBuffer();
        JSONArray tempArr = tempObj.getJSONArray("itemInfoList");
        if (tempArr == null || tempArr.isEmpty()) {
            // 商品数据为空, 不需操作
            log.debug("京东商品数据为空, msgkey : " + msgkey);
            return;
        }

        for (Object obj : tempArr) {

            String itemId = "0";
            // 商品数据，商品字表SKU数据
            JSONObject itemObj = null;
            try {

                itemObj = JSONObject.parseObject(obj.toString(), Feature.OrderedField);
                //System.out.println("线上接送消息体===>" + itemObj.toJSONString());
                itemId = itemObj.getLong("wareId").toString();
                tids.append(",").append(itemId);
                sellerNick = itemObj.getString("nick");
                // 根据平台商品id查询数据库,判断该数据是新增或是修改
                String selectSql = "SELECT id FROM t_iesjingdongware WHERE wareId = ?";
                int id = Tools.getInt(QueryEngine.getInstance().doQueryOne(selectSql, new Object[]{itemId}), -1);
                if (id < 0) {
                    // 数据不存在, 新增商品
                    //System.out.println("传入的参数=====" + itemObj.toJSONString());
                    jingDongItemDao.saveJdItem(itemObj);

                } else {
                    // 数据存在,根据查询的id 更新数据
                    jingDongItemDao.updateJdItem(itemObj, id);
                }
                localLogService.insertLogForJd(null, itemId, topic, msgkey, sellerNick, null, 0);
            } catch (Exception e) {
                // 发生异常,处理
                // 获取流
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                // 逐条将错误信息以消息发送到线上发送到线上
                JSONObject errObj = new JSONObject();
                errObj.put("flag", 0);
                errObj.put("platid", itemId);
                errObj.put("sellernick", sellerNick);
                errObj.put("topic", topic);
                errObj.put("tag", tag);
                errObj.put("msgkey", msgkey);
                // 线下消费报错的主机 ip
                errObj.put("ip", NetUtils.getLocalAddress());
                // 将错误以流写出
                e.printStackTrace(pw);
                errObj.put("errmsg", sw.toString());
                errObj.put("sendtime", System.currentTimeMillis());
                try {
                    sendMqServies.sendMqObj(errObj, pconf.getProperty("ons.jdLogErrTopic"), tag);
                } catch (Exception e1) {
                    e1.printStackTrace();
                    log.debug("京东商品发送错误信息失败");
                }
                log.debug("商品插入失败 : tid :" + itemId + "msgkey : " + msgkey + sw.toString());
                // 处理异常  1.将错误信息发送到线上  2. 将错误信息保存到本地数据库
                countFaild++;
                // 插入本地错误
                localLogService.insertLogForJd(e.getMessage(), itemId, topic, msgkey, sellerNick, null, 1);
            }

        }
        retObj.put("flag", 0);
        retObj.put("tag", tag);
        retObj.put("sellernick", sellerNick);
        retObj.put("msgkey", msgkey);
        retObj.put("msgsize", tempArr.size());
        retObj.put("topic", topic);
        retObj.put("tids", tids.deleteCharAt(0).toString());
        retObj.put("successcount", tempArr.size() - countFaild);
        retObj.put("failedcount", countFaild);
        try {
            sendMqServies.sendMqRetLogObj(retObj, jdLogRetTopic, tag, sellerNick);
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("京东商品发送回执信息失败");
        }
    }


    /**
     * 保存商品数据
     *
     * @param itemInfoObj
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveJdItem(JSONObject itemInfoObj) throws ParseException {
        long id = 0L;
        JingDongItemDao jingDongItemDao = ApplicationContextHandle.getBean(JingDongItemDao.class);
        if (itemInfoObj != null) {
            System.out.println("要插入的itemInfoObj1111=====" + itemInfoObj.toJSONString());
            JSONObject jsonObject = itemInfoObj;
            String productTableName = "T_IESJINGDONGWARE";

            synchronized (this) {
                // 校验字段
                JsonKeyCheck checkjson = ApplicationContextHandle.getBean(JsonKeyCheck.class);
                itemInfoObj = checkjson.checkJsonkey(itemInfoObj, productTableName, checkjson.getInsertcolsmap());
            }
            if (itemInfoObj.get("features")!=null){
                itemInfoObj.replace("features",itemInfoObj.getString("features"));
            }
            //处理Date格式的数据
            if (itemInfoObj.getLong("modified")!=null) {
                itemInfoObj.replace("modified", new Date(itemInfoObj.getLong("modified")));
            }
            if (itemInfoObj.getLong("created")!=null) {
                itemInfoObj.replace("created", new Date(itemInfoObj.getLong("created")));
            }
            if (itemInfoObj.getLong("offlineTime") != null) {
                itemInfoObj.replace("offlineTime", new Date(itemInfoObj.getLong("offlineTime")));
            }
            if (itemInfoObj.getLong("onlineTime") != null) {
                itemInfoObj.replace("onlineTime", new Date(itemInfoObj.getLong("onlineTime")));
            }
            // 获取子表的 sequences , 添加 必须字段
            id = getSqunceService.getSqunce(productTableName);
            itemInfoObj.put("id", id);
            JSONObject adWords = itemInfoObj.getJSONObject("adWords");
            if (adWords != null) {
                itemInfoObj.put("adWords", "urlWords:'" + adWords.getString("urlWords") + "',words:'" + adWords.getString("words") + "'");
            }
            Set<String> keys = itemInfoObj.keySet();
            for (String key : keys) {
                if (itemInfoObj.get(key)==null){
                    itemInfoObj.remove(key);
                }
            }
            //System.out.println("要插入的itemInfoObj222=====" + itemInfoObj.toJSONString());
            Object[] objArr = itemInfoObj.values().toArray();
            // 拼接 sql
            String columnName = packageJsonSqlUtil.packageInsertCloumnName(itemInfoObj);
            String columnValue = packageJsonSqlUtil.packageInsertColumnValue(objArr);
            String sql = "insert into t_iesjingdongware (" + columnName + ") values (" + columnValue + ")";
            log.debug("插入京东商品表 sql : " + sql);
            //System.out.println(Arrays.toString(objArr));
            //System.out.println("插入京东商品表 sql : " + sql);
            QueryEngine.getInstance().executeUpdate(sql, objArr);
            // 在执行完之后需要更改主表的 istrans 字段为 0
            String sql2 = "update t_iesjingdongware SET istrans = 0 WHERE id = ?";
            QueryEngine.getInstance().executeUpdate(sql2, new Object[]{id});
            jingDongItemDao.executeJdSku(jsonObject, id, false);
        } else {
            log.debug("主表数据为空 id " + id);
        }
    }

    /**
     * 修改商品主表数据
     *
     * @param itemObj
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateJdItem(JSONObject itemObj, long id) throws ParseException {
        //System.out.println("更新表");
        JingDongItemDao jingDongItemDao = ApplicationContextHandle.getBean(JingDongItemDao.class);
        if (itemObj != null) {
            JSONObject jsonObject = itemObj;
            String orderTableName = "T_IESJINGDONGWARE";
            synchronized (this) {
                // 校验字段
                JsonKeyCheck checkjson = ApplicationContextHandle.getBean(JsonKeyCheck.class);
                itemObj = checkjson.checkJsonkey(itemObj, orderTableName, checkjson.getUpdatecolsmap());
            }
            //处理Date格式的数据
            if (itemObj.get("features")!=null){
                itemObj.replace("features",itemObj.getString("features"));
            }
            if (itemObj.getLong("modified")!=null) {
                itemObj.replace("modified", new Date(itemObj.getLong("modified")));
            }
            if (itemObj.getLong("offlineTime")!=null) {
                itemObj.replace("offlineTime", new Date(itemObj.getLong("offlineTime")));
            }
            if (itemObj.getLong("onlineTime") != null) {
                itemObj.replace("onlineTime", new Date(itemObj.getLong("onlineTime")));
            }
            JSONObject adWords = itemObj.getJSONObject("adWords");
            if (adWords != null) {
                itemObj.put("adWords", "urlWords:'" + adWords.getString("urlWords") + "',words:'" + adWords.getString("words") + "'");
            }
            Set<String> keys = itemObj.keySet();
            for (String key : keys) {
                if (itemObj.get(key)==null){
                    itemObj.remove(key);
                }
            }
            String params = packageJsonSqlUtil.packageUpdateCloumnName(itemObj);
            Object[] objArr = packageJsonSqlUtil.packageUpdateColumnValue(itemObj);
            //System.out.println("要更新的itemObj=====" + itemObj.toJSONString());
            String sql = "update t_iesjingdongware set " + params + " where id = ?";
            //System.out.println("更新京东商品表 sql : " + sql);
            QueryEngine.getInstance().executeUpdate(sql, ArrayUtils.add(objArr, id));
            String sql2 = "update t_iesjingdongware SET istrans = 0 WHERE id = ?";
            QueryEngine.getInstance().executeUpdate(sql2, new Object[]{id});
            jingDongItemDao.executeJdSku(jsonObject, id, true);
            System.out.println("更新完成");
        } else {
            log.error("商品主表数据为空");
        }
    }

    /**
     * 保存商品SKU数据
     *
     * @param skuInfoObj
     */
    public void saveJdSku(JSONObject skuInfoObj, long itemId) throws ParseException {
        long id = 0L;
        if (skuInfoObj != null) {
            String productTableName = "T_IESJINGDONGWARESKU";

            synchronized (this) {
                // 校验字段
                JsonKeyCheck checkjson = ApplicationContextHandle.getBean(JsonKeyCheck.class);
                skuInfoObj = checkjson.checkJsonkey(skuInfoObj, productTableName, checkjson.getInsertcolsmap());
            }
            if (skuInfoObj.getLong("modified") != null) {
                skuInfoObj.replace("modified", new Date(skuInfoObj.getLong("modified")));
            }
            if (skuInfoObj.getLong("created")!=null) {
                skuInfoObj.replace("created", new Date(skuInfoObj.getLong("created")));
            }
            // 获取子表的 sequences , 添加 必须字段
            id = getSqunceService.getSqunce(productTableName);
            skuInfoObj.put("id", id);
            skuInfoObj.put("IESJINGDONGWAREID", itemId);
            //log.debug("要插入字表的数据==》" + skuInfoObj.toJSONString());
            Object[] objArr = skuInfoObj.values().toArray();
            // 拼接 sql
            String columnName = packageJsonSqlUtil.packageInsertCloumnName(skuInfoObj);
            String columnValue = packageJsonSqlUtil.packageInsertColumnValue(objArr);

            String sql = "insert into t_iesjingdongwaresku (" + columnName + ") values (" + columnValue + ")";
            //log.debug("插入京东商品SKU子表 sql : " + sql);
            QueryEngine.getInstance().executeUpdate(sql, objArr);
        } else {
            log.debug("商品SKU子表数据为空" + id);
        }
    }

    /**
     * 修改商品SKU子表数据
     *
     * @param skuObj
     * @param id
     * @return
     */
    public void updateJdSku(JSONObject skuObj, long id) throws ParseException {
        if (skuObj != null) {
            String orderTableName = "T_IESJINGDONGWARESKU";
            synchronized (this) {
                // 校验字段
                JsonKeyCheck checkjson = ApplicationContextHandle.getBean(JsonKeyCheck.class);
                skuObj = checkjson.checkJsonkey(skuObj, orderTableName, checkjson.getUpdatecolsmap());
            }
            if (skuObj.getLong("modified")!=null) {
                skuObj.replace("modified", new Date(skuObj.getLong("modified")));
            }
            //skuObj.replace("created",new Date(skuObj.getLong("created")));
            String params = packageJsonSqlUtil.packageUpdateCloumnName(skuObj);
            Object[] objArr = packageJsonSqlUtil.packageUpdateColumnValue(skuObj);

            String sql = "update t_iesjingdongwaresku set " + params + " where id = ?";
            QueryEngine.getInstance().executeUpdate(sql, ArrayUtils.add(objArr, id));
            System.out.println("修改商品子表成功");
        } else {
            log.debug("商品sku子表数据为空");
        }
    }

    public void executeJdSku(JSONObject itemObj, long itemId, boolean flag) throws ParseException {
        JingDongItemDao jingDongItemDao = ApplicationContextHandle.getBean(JingDongItemDao.class);
        JSONArray skuArr = itemObj.getJSONArray("skuDataList");
        for (int i = 0; i < skuArr.size(); i++) {
            JSONArray skuInfoArr = skuArr.getJSONArray(i);
            if (skuInfoArr == null || skuInfoArr.isEmpty()) {
                log.debug("sku数据为空");
                continue;
            }
            for (int j = 0; j < skuInfoArr.size(); j++) {
                Long skuId = 0L;
                JSONObject skuObj = skuInfoArr.getJSONObject(j);
                //如果主表是更新，则需要判断字表是更新还是插入，如果主表是插入，则字表也直接是插入
                if (skuObj == null || skuObj.size() == 0){
                    continue;
                }
                if (flag) {
                    skuId = skuObj.getLong("skuId");
                    String sql = "SELECT id FROM t_iesjingdongwaresku WHERE skuId = ?";
                    int id2 = Tools.getInt(QueryEngine.getInstance().doQueryOne(sql, new Object[]{skuId}), -1);
                    if (id2 < 0) {
                        // 数据不存在, 新增商品
                        jingDongItemDao.saveJdSku(skuObj, itemId);
                    } else {
                        // 数据存在,根据查询的id 更新数据
                        jingDongItemDao.updateJdSku(skuObj, id2);
                    }
                } else {
                    jingDongItemDao.saveJdSku(skuObj, itemId);
                }
            }
        }
    }
}
